package com.xzw.cameratest.calendardialog;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.xzw.cameratest.R;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


/**
 * Created by 46085 on 2019/9/6.
 */

public class CalendarDialog extends DialogFragment {

    private View mDialogView;

    private LinearLayout lly_calendar_title;
    private View titleView;

    private ImageView iv_calendar_last_month;
    private ImageView iv_calendar_next_month;
    private TextView tv_calendar_month;

    private RecyclerView rv_calendar_days;
    private CalendarRVAdapter calendarRVAdapter;
    private GridLayoutManager gridLayoutManager;

    protected int mScreenWidth = 0;
    protected int mScreenHeight = 0;
    protected float mScreenScale = 0f;

    private List<DateBean> dateBeans;
    private Calendar calendar;
    private Calendar calendarSelect;

    private CalendarRVAdapter.OnItemClickListener onItemClickListener;
    private OnClickListener onClickListener;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DisplayMetrics metric = new DisplayMetrics();
        if (getActivity() != null && getActivity().getWindowManager() != null) {
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(metric);
        }
        mScreenScale = metric.density; //屏幕像素密度
        mScreenWidth = metric.widthPixels; // 屏幕宽度（像素）
        mScreenHeight = metric.heightPixels; // 屏幕高度（像素）
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (getDialog().getWindow() != null) {
            getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            getDialog().getWindow().setGravity(Gravity.BOTTOM);
        }

        mDialogView = inflater.inflate(R.layout.layout_calendar_dialog, null);

        lly_calendar_title = (LinearLayout) mDialogView.findViewById(R.id.lly_calendar_title);

        if (titleView != null) {
            lly_calendar_title.setVisibility(View.VISIBLE);
            lly_calendar_title.addView(titleView);
        }

        iv_calendar_last_month = (ImageView) mDialogView.findViewById(R.id.iv_calendar_last_month);
        iv_calendar_next_month = (ImageView) mDialogView.findViewById(R.id.iv_calendar_next_month);
        tv_calendar_month = (TextView) mDialogView.findViewById(R.id.tv_calendar_month);

        rv_calendar_days = (RecyclerView) mDialogView.findViewById(R.id.rv_calendar_days);


        if (calendar == null) {
            calendar = (Calendar) Calendar.getInstance().clone();
            calendarSelect = (Calendar) calendar.clone();
        }

        dateBeans = getSelectMonthDateBeans(calendar);
//        for (DateBean dateBean : dateBeans) {
//            dateBean.setSelect(dateBean.getDay() == calendar.get(Calendar.DAY_OF_MONTH));
//        }

        gridLayoutManager = new GridLayoutManager(getContext(), 7);
        calendarRVAdapter = new CalendarRVAdapter(getContext());
        calendarRVAdapter.setDateBeans(dateBeans);
        rv_calendar_days.setLayoutManager(gridLayoutManager);
        rv_calendar_days.setAdapter(calendarRVAdapter);

        tv_calendar_month.setText(
                String.valueOf(calendar.get(Calendar.YEAR)) + "-"
                        + String.format("%02d", calendar.get(Calendar.MONTH) + 1));

        initListener();

        return mDialogView;
    }

    @Override
    public void onStart() {
        super.onStart();

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();

        params.width = ViewGroup.LayoutParams.MATCH_PARENT;
        params.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        window.setAttributes(params);
    }

    private void initListener () {
        iv_calendar_last_month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.add(Calendar.MONTH, -1);
                tv_calendar_month.setText(
                        String.valueOf(calendar.get(Calendar.YEAR)) + "-"
                                + String.format("%02d", calendar.get(Calendar.MONTH) + 1));
                dateBeans = getSelectMonthDateBeans(calendar);
                calendarRVAdapter.setDateBeans(dateBeans);
                calendarRVAdapter.notifyDataSetChanged();

                if (onClickListener != null) {
                    onClickListener.onMonthChanged(
                            calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH) + 1,
                            dateBeans);
                }
            }
        });

        iv_calendar_next_month.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.add(Calendar.MONTH, 1);
                tv_calendar_month.setText(
                        String.valueOf(calendar.get(Calendar.YEAR)) + "-"
                                + String.format("%02d", calendar.get(Calendar.MONTH) + 1));
                dateBeans = getSelectMonthDateBeans(calendar);
                calendarRVAdapter.setDateBeans(dateBeans);
                calendarRVAdapter.notifyDataSetChanged();

                if (onClickListener != null) {
                    onClickListener.onMonthChanged(
                            calendar.get(Calendar.YEAR),
                            calendar.get(Calendar.MONTH) + 1,
                            dateBeans);
                }
            }
        });

        onItemClickListener = new CalendarRVAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, DateBean dateBean) {
                if (onClickListener != null && dateBean != null && !TextUtils.isEmpty(dateBean.getShownDay())) {
                    onClickListener.onDateSelect(dateBean);
                }
            }
        };
        calendarRVAdapter.setOnItemClickListener(onItemClickListener);
    }

    private List<DateBean> getSelectMonthDateBeans (Calendar calendar) {
        List<DateBean> dateBeans = new ArrayList<>();

        Calendar calendar1MonthBegin = (Calendar) calendar.clone();
        calendar1MonthBegin.set(Calendar.DAY_OF_MONTH, 1);
        // 1-星期天 7-星期六
        int dayOfWeek = calendar1MonthBegin.get(Calendar.DAY_OF_WEEK);
        //上月的最后几天展示在本月
        int emptyCount = dayOfWeek - 1;// 从周一开始
        emptyCount = (dayOfWeek - 1) % 7;// 从周日开始
        // 当月的最大天数
        int maxDays = calendar1MonthBegin.getActualMaximum(Calendar.DAY_OF_MONTH);

        //当月有效日期+1号前空白日期个数>35,则当月需要6行
//        int maxRows = emptyCount + maxDays > 35 ? 6 : 5;
        int maxRows = 6;

        for (int i = 0; i < (maxRows * 7); i++) {
            DateBean dateBean = new DateBean();
            if (i < emptyCount) {
                // 上个月空白天
                dateBean.setEnable(false);
            } else if (i >= emptyCount + maxDays) {
                // 下个月空白天
                dateBean.setEnable(false);
            } else {
                dateBean.setYear(calendar.get(Calendar.YEAR));
                dateBean.setMonth(calendar.get(Calendar.MONTH));
                dateBean.setShownDay(String.valueOf(i - emptyCount + 1));
                dateBean.setDay(i - emptyCount + 1);
                dateBean.setDayOfWeek(i % 7 + 1);
                dateBean.setEnable(true);
                if (dateBean.getYear() == calendarSelect.get(Calendar.YEAR)
                        && dateBean.getMonth() == calendarSelect.get(Calendar.MONTH)
                        && dateBean.getDay() == calendarSelect.get(Calendar.DAY_OF_MONTH)) {
                    dateBean.setSelect(true);
                } else {
                    dateBean.setSelect(false);
                }
            }
            dateBeans.add(dateBean);
        }

        return dateBeans;
    }

    public void setTitleView (View view) {
        this.titleView = view;
    }

    public void setCalendar(Calendar calendar) {
        this.calendar = calendar;
        this.calendarSelect = (Calendar) calendar.clone();
    }

    public void notifyDataChanged () {
        calendarRVAdapter.notifyDataSetChanged();
    }

    public void refreshMonthInfo () {
        if (onClickListener != null) {
            onClickListener.onMonthChanged(
                    calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH) + 1,
                    dateBeans);
        }
    }

    public void setOnClickListener(OnClickListener onClickListener) {
        this.onClickListener = onClickListener;
    }

    public interface OnClickListener {
        void onMonthChanged(int year, int month, List<DateBean> dateBeans);
        void onDateSelect(DateBean dateBean);
    }
}
